package com.cloudweb.oa.controller;

import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONPObject;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.attendance.ShiftScheduleMgr;
import com.redmoon.oa.dept.DeptDb;
import com.redmoon.oa.dept.DeptUserDb;
import com.redmoon.oa.flow.WorkflowMgr;
import com.redmoon.oa.hr.SignMgr;
import com.redmoon.oa.oacalendar.OACalendarDb;
import com.redmoon.oa.person.UserDb;
import io.swagger.annotations.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.redmoon.oa.attendance.BMapUtil;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.pvg.Privilege;
import com.redmoon.oa.visual.FormDAO;

import cn.js.fan.db.SQLFilter;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;

/**
 * @Description:
 * @author:
 * @Date: 2017-9-26下午03:09:04
 */
@Api(tags = "排班")
@Controller
@RequestMapping("/attendance")
public class ShiftController {
    @Autowired
    private HttpServletRequest request;

    @ApiOperation(value = "保存排班调整", notes = "保存排班调整", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "数据", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/saveShiftAdjust", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> saveShiftAdjust(@RequestParam(value = "data") String data) {
        boolean re = false;

        JSONArray ary = JSONArray.parseArray(data);

        Privilege pvg = new Privilege();
        String creator = pvg.getUser(request);
        String unitCode = pvg.getUserUnitCode(request);

        if (ary == null || ary.size()==0) {
            re = true;
        } else {
            for (Object o : ary) {
                com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject)o;
                String userName = json.getString("userName");
                String strDate = json.getString("date");
                long shiftId = json.getLongValue("shiftId");
                int operate = json.getIntValue("operate"); // 0是清除 1是新增
                if (operate == 0) {
                    shiftId = 0; // 0 表示生成清除记录
                }

                // 调整某用户某天的班次
                re = adjustShift(userName, strDate, shiftId, creator, unitCode);
            }
        }

        return new Result<>(re);
    }

    /**
     * 调整某用户某天的班次
     *
     * @param userName
     * @param strDate
     * @param shift    如果为-1，表示删除调整记录
     * @param creator
     * @param unitCode
     * @Description:
     */
    public boolean adjustShift(String userName, String strDate, long shift, String creator, String unitCode) {
        String sql = "select id from ft_shift_adjust where user_name=" + StrUtil.sqlstr(userName) + " and mydate=" + SQLFilter.getDateStr(strDate, "yyyy-MM-dd");
        String formCode = "shift_adjust";
        FormDb fd = new FormDb();
        fd = fd.getFormDb(formCode);
        FormDAO fdao = new FormDAO(fd);
        try {
            Vector v = fdao.list(formCode, sql);
            if (v.size() > 0) {
                // 已存在，则判断值是否相等，不相等则重写
                Iterator ir = v.iterator();
                if (ir.hasNext()) {
                    fdao = (FormDAO) ir.next();

                    // 判断与正常排班的班次是否一致，如果一致，则说明不需要调整，直接删掉调班记录
                    FormDAO fdaoNormal = ShiftScheduleMgr.getShiftNormal(fdao.getFieldValue("user_name"), DateUtil.parse(fdao.getFieldValue("mydate"), "yyyy-MM-dd"));
                    if (fdaoNormal != null) {
                        if (shift == fdaoNormal.getId()) {
                            fdao.del();
                            return true;
                        }
                    }

                    // 删除调整记录
                    if (shift == -1 || shift == 0) {
                        fdao.del();
                        return true;
                    }

                    long oldShift = StrUtil.toLong(fdao.getFieldValue("shift"));
                    if (oldShift != shift) {
                        fdao.setFieldValue("shift", String.valueOf(shift));
                        fdao.save();
                    }
                }
            } else {
                if (shift != -1) {
                    // 判断与正常排班的班次是否一致，如果一致，则说明不需要调整
                    FormDAO fdaoNormal = ShiftScheduleMgr.getShiftNormal(fdao.getFieldValue("user_name"), DateUtil.parse(strDate, "yyyy-MM-dd"));
                    if (fdaoNormal != null) {
                        if (shift == fdaoNormal.getId()) {
                            return true;
                        }
                    }

                    fdao.setFieldValue("user_name", userName);
                    fdao.setFieldValue("mydate", strDate);
                    fdao.setFieldValue("shift", String.valueOf(shift));
                    fdao.setCreator(creator);
                    fdao.setUnitCode(unitCode);
                    fdao.create();
                }
            }
        } catch (ErrMsgException | SQLException e) {
            LogUtil.getLog(getClass()).error(e);
            return false;
        }
        return true;
    }

    @ApiOperation(value = "班次列表", notes = "班次列表", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @PreAuthorize("hasAnyAuthority('admin', 'kaoqin.admin')")
    @ResponseBody
    @RequestMapping(value = "/listShift", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listShift() {
        JSONArray ary = new JSONArray();
        ShiftScheduleMgr ssm = new ShiftScheduleMgr();
        for (Object o : ssm.listShift()) {
            FormDAO fdao = (FormDAO) o;
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("id", fdao.getId());
            json.put("color", fdao.getFieldValue("color"));
            json.put("name", fdao.getFieldValue("name"));
            ary.add(json);
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "班次调整列表", notes = "班次列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptCode", value = "部门编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "showYear", value = "年份", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "showMonth", value = "月份，从1开始", required = true, dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @PreAuthorize("hasAnyAuthority('admin', 'kaoqin.admin')")
    @ResponseBody
    @RequestMapping(value = "/listForAdjust", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listForAdjust(@RequestParam(value = "deptCode") String deptCode, @RequestParam(value = "showYear") Integer showYear, @RequestParam(value = "showMonth") Integer showMonth) {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        int dayCount = DateUtil.getDayCount(showYear, showMonth-1);
        jsonObject.put("dayCount", dayCount);

        DeptDb deptDb = new DeptDb();
        deptDb = deptDb.getDeptDb(deptCode);
        Vector<DeptDb> dv = new Vector<>();
        deptDb.getAllChild(dv, deptDb);
        StringBuilder depts = new StringBuilder(StrUtil.sqlstr(deptCode));
        for (Object o : dv) {
            deptDb = (DeptDb) o;
            depts.append(",").append(StrUtil.sqlstr(deptDb.getCode()));
        }

        com.redmoon.oa.Config cfg = new com.redmoon.oa.Config();
        boolean showByDeptSort = cfg.getBooleanProperty("show_dept_user_sort");
        String orderField = showByDeptSort ? "du.orders" : "u.orders";
        JSONArray ary = new JSONArray();

        DeptUserDb du = new DeptUserDb();
        String sql = "select du.ID from dept_user du, users u where du.user_name=u.name and u.isValid=1 and du.DEPT_CODE in (" + depts + ") order by du.DEPT_CODE asc, " + orderField + " asc";
        java.util.Date start = DateUtil.getDate(showYear, showMonth-1, 1);
        OACalendarDb oacal = new OACalendarDb();
        UserDb user = new UserDb();
        for (Object o : du.listBySQL(sql)) {
            DeptUserDb pu = (DeptUserDb) o;
            if (!"".equals(pu.getUserName())) {
                user = user.getUserDb(pu.getUserName());
            } else {
                continue;
            }

            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("userName", user.getName());
            json.put("realName", user.getRealName());

            JSONArray aryUser = new JSONArray();
            for (int i = 0; i <= dayCount - 1; i++) {
                // 判断是否为非工作日
                Date d = DateUtil.addDate(start, i);
                oacal = (OACalendarDb) oacal.getQObjectDb(d);
                boolean isWorkDay;
                if (oacal != null && oacal.getInt("date_type") != OACalendarDb.DATE_TYPE_WORK) {
                    isWorkDay = false;
                } else {
                    isWorkDay = true;
                }

                if (oacal == null) {
                    oacal = new OACalendarDb();
                }

                boolean isAdjust = false;
                Object[] objAry = ShiftScheduleMgr.getShiftDAO(pu.getUserName(), d);
                FormDAO fdao = null;
                fdao = (FormDAO) objAry[0];
                isAdjust = (Boolean) objAry[1];
                String shiftName = "";
                String origBgColor = ""; // 记录的背景色，如果是调整过的，则为调整后班次的背景色，如果未调整，则为进入页面时初始背景色
                long origShift = -1;
                if (fdao != null) {
                    // 0 表示班次被清除
                    if ("0".equals(fdao.getFieldValue("shift"))) {
                        origBgColor = "#ffffff";
                        shiftName = "无班次";
                    } else {
                        origBgColor = fdao.getFieldValue("color");
                        shiftName = fdao.getFieldValue("name");
                    }
                    origShift = fdao.getId();
                } else {
                    shiftName = "默认排班";
                }

                com.alibaba.fastjson.JSONObject jObj = new com.alibaba.fastjson.JSONObject();
                jObj.put("day", i + 1);
                jObj.put("shiftName", shiftName);
                jObj.put("isAdjusted", isAdjust);
                jObj.put("bgColor", origBgColor);
                jObj.put("shiftId", origShift);
                jObj.put("isWorkDay", isWorkDay);
                aryUser.add(jObj);
            }
            json.put("days", aryUser);
            ary.add(json);
        }
        jsonObject.put("list", ary);
        return new Result<>(jsonObject);
    }
}
